package com.gitee.linmt.util;

import com.gitee.linmt.entity.UserInfo;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

/**
 * @author linmt
 */
public class PasswordUtil {

    public static final String PASSWORD_ALGORITHM_NAME = "MD5";
    public static final Integer PASSWORD_HASH_ITERATIONS = 2;

    /**
     * md5 设置盐和加密密码
     * 散列算法是：md5(md5(密码+username+randomNumber))
     * @param userInfo 用户信息
     */
    public static void setSaltAndEncodedPassword(UserInfo userInfo) {
        String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
        userInfo.setSalt(salt);
        SimpleHash hash = new SimpleHash(
                PasswordUtil.PASSWORD_ALGORITHM_NAME,
                userInfo.getPassword(),
                salt,
                PasswordUtil.PASSWORD_HASH_ITERATIONS);
        userInfo.setPassword(hash.toHex());
    }

    public static void main(String[] args) {
        UserInfo adminInfo = new UserInfo();
        adminInfo.setUsername("admin");
        adminInfo.setPassword("admin");
        PasswordUtil.setSaltAndEncodedPassword(adminInfo);
        System.out.println(adminInfo.toString());
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("user");
        userInfo.setPassword("user");
        PasswordUtil.setSaltAndEncodedPassword(userInfo);
        System.out.println(userInfo.toString());
    }
}
